package com.heima.homeservicemanagementsystem.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.heima.homeservicemanagementsystem.config.annotation.RestControllerMapping;
import com.heima.homeservicemanagementsystem.entity.SysUser;
import com.heima.homeservicemanagementsystem.entity.SysUserRole;
import com.heima.homeservicemanagementsystem.entity.dto.Option;
import com.heima.homeservicemanagementsystem.mapper.SysUserRoleMapper;
import com.heima.homeservicemanagementsystem.module.PageParams;
import com.heima.homeservicemanagementsystem.module.Result;
import com.heima.homeservicemanagementsystem.service.SysUserService;
import com.heima.homeservicemanagementsystem.utils.PasswordUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;

import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author susu
 * @Date 2024/11/24
 */
//@RestController
//@RequestMapping("/sysUser")
@RestControllerMapping("/sysUser")
@Tag(name = "用户管理")
@Slf4j
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @GetMapping("/info/{id}")
    @Operation(summary = "通过ID查询单条数据", parameters = {
            @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
    })
    @ApiOperationSupport(order = 1)
    public Result<SysUser> get(@PathVariable String id) {
        return Result.success(sysUserService.getById(id));
    }

    @GetMapping("/info")
    @Operation(summary = "获取用户的数据(没角色)")
    @ApiOperationSupport(order = 1)
    public Result<SysUser> getuserinfo() {
        String loginIdAsString = StpUtil.getLoginIdAsString();
        return Result.success(sysUserService.getById(loginIdAsString));
    }

    @GetMapping("/infoAndRole")
    @Operation(summary = "获取用户的数据(没角色)")
    @ApiOperationSupport(order = 1)
    public Result<SysUser> getuserinfoandrole() {
        String loginIdAsString = StpUtil.getLoginIdAsString();
        SysUser user = sysUserService.getById(loginIdAsString);
        user.setRoles(sysUserService.getRoles(user.getId()));
        return Result.success(user);
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询用户信息")
    @ApiOperationSupport(order = 2)
    public Result<Page<SysUser>> pageQuery(@RequestBody PageParams<SysUser> pageParams) {
        //查询参数
        SysUser params = pageParams.getParams();
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(StrUtil.isNotBlank(params.getNickname()), SysUser::getNickname, params.getNickname());
        Page<SysUser> page = sysUserService.page(pageParams.getPage(), lqw);
        page.getRecords().forEach(item -> {
            item.setRoles(sysUserService.getRoles(item.getId()));
        });
        return Result.success(page);
    }

    /**
     * 有小bug不影响使用
     *
     * @param user
     * @return com.heima.homeservicemanagementsystem.module.Result<java.util.List < com.heima.homeservicemanagementsystem.entity.SysUser>>
     * @author jinchengfei
     * @create 2025/3/25
     **/

    @PostMapping("/list")
    @Operation(summary = "列表查询（不带分页）")
    @ApiOperationSupport(order = 2)
    public Result<List<SysUser>> pageQuery(@RequestBody SysUser user) {
        log.info("接收的数据:{}", user);
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();

        lqw.like(StrUtil.isNotBlank(user.getNickname()), SysUser::getNickname, user.getNickname());
        lqw.like(StrUtil.isBlankIfStr(user.getSex()), SysUser::getSex, user.getSex());
        List<SysUser> list = sysUserService.list(lqw);
        list.forEach(item -> {
            item.setRoles(sysUserService.getRoles(item.getId()));
        });
        return Result.success(list);
    }

    @PostMapping("/search")
    @Operation(summary = "列表查询搜索")
    @ApiOperationSupport(order = 2)
    public Result<List<SysUser>> search(@RequestBody SysUser user) {
        log.info("接收的数据:{}", user);
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();

        lqw.eq(user.getId() != null, SysUser::getId, user.getId());
        lqw.like(user.getUsername() != null, SysUser::getUsername, user.getUsername());
        lqw.like(user.getNickname() != null, SysUser::getNickname, user.getNickname());
        lqw.eq(user.getPhone() != null, SysUser::getPhone, user.getPhone());
        lqw.eq(user.getGithubLogin() != null, SysUser::getGithubLogin, user.getGithubLogin());
        lqw.eq(user.getGiteeLogin() != null, SysUser::getGiteeLogin, user.getGiteeLogin());
        lqw.eq(user.getEmail() != null, SysUser::getEmail, user.getEmail());
        lqw.eq(user.getSex() != null, SysUser::getSex, user.getSex());
        lqw.eq(user.getStatus() != null, SysUser::getStatus, user.getStatus());
        List<SysUser> list = sysUserService.list(lqw);
        list.forEach(item -> {
            item.setRoles(sysUserService.getRoles(item.getId()));
        });
//        return Result.success();
        return Result.success(list);
    }

    @SaIgnore
    @PostMapping("/insert")
    @Operation(summary = "新增用户及用户角色")
    @ApiOperationSupport(order = 3)
    public Result insert(@RequestBody SysUser sysUser) {
        //生成16为的随机盐
        String s = RandomUtil.randomString(16);
        sysUser.setSlat(s);
        String password = PasswordUtils.encrypt(s, sysUser.getPassword());
        sysUser.setPassword(password);
        Result validationResult = extracted(sysUser);
        if (validationResult != null) {
            // 如果返回的结果不是 null，则表示存在错误，直接返回错误
            return validationResult;
        }
        //密码加密
        if (sysUserService.save(sysUser)) {
            List<Option> roles = sysUser.getRoles();
//            System.out.println(roles);

            if (sysUser.getRoles().size() > 0) {
                List<Object> rolesIds = roles.stream().map(Option::getValue).toList();
                log.info("数据：{}", rolesIds);
                sysUserService.insertRoles(sysUser.getId(), rolesIds);
            } else {
                List<SysUserRole> sysUserRoles = userRoleMapper.selectList(new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()).eq("role_id", "1895452596287164418"));
                boolean empty = CollectionUtils.isEmpty(sysUserRoles);
//        log.info("是否为空:{}", empty);
                if (empty) {
                    ArrayList<Object> roid = new ArrayList<>();
                    roid.add("1895452596287164418");
                    insertRole(sysUser.getId(), roid);
                    return Result.success("注册成功");
                } else {
                    return Result.error("用户已拥有该角色，无需再次分配");
                }
            }
            return Result.success();
        }
        return Result.error();
    }

    private void insertRole(String userId, ArrayList<Object> roles) {
        // 插入角色信息
        for (Object role : roles) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(role.toString());

            int insertRoleResult = userRoleMapper.insert(sysUserRole);
            if (insertRoleResult <= 0) {
                // 如果插入失败，抛出异常，Spring 会自动回滚事务
//                触发回滚前面的事务，回滚事务
                throw new RuntimeException("角色注册失败，用户已存在");

            }
        }
    }

    private Result extracted(SysUser sysUser) {
        if (sysUserService.exists(new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()))) {
            return Result.error("用户名已存在");
        }
        if (sysUserService.exists(new QueryWrapper<SysUser>().eq("email", sysUser.getEmail()))) {
            return Result.error("邮箱已存在");
        }
        if (sysUserService.exists(new QueryWrapper<SysUser>().eq("github_login", sysUser.getGithubLogin()))) {
            return Result.error("github账号已存在");
        }
        if (sysUserService.exists(new QueryWrapper<SysUser>().eq("gitee_login", sysUser.getGiteeLogin()))) {
            return Result.error("gitee账号已存在");
        }
        if (sysUserService.exists(new QueryWrapper<SysUser>().eq("phone", sysUser.getPhone()))) {
            return Result.error("此电话已被注册");
        }
        return null;
    }

    /**
     * 更新数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */

    @PutMapping("update")
    @Operation(summary = "更新数据")
    @ApiOperationSupport(order = 4)
    public Result<Boolean> update(@RequestBody SysUser sysUser) {
        if (sysUser.getRoles().size() > 0) {
            sysUserService.deleteRoles(sysUser.getId());
        }
        String s = RandomUtil.randomString(16);
        sysUser.setSlat(s);
        String password = PasswordUtils.encrypt(s, sysUser.getPassword());
        sysUser.setPassword(password);

        if (sysUserService.updateById(sysUser)) {
            if (sysUser.getRoles() != null) {
                List<Option> roles = sysUser.getRoles();
                if (sysUser.getRoles().size() > 0) {
                    List<Object> rolesIds = roles.stream().map(Option::getValue).toList();
                    sysUserService.insertRoles(sysUser.getId(), rolesIds);
                }
            }
            return Result.success();
        }
        return Result.error();
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */

    @GetMapping("/delete/{id}")
    @Operation(summary = "通过主键删除单条数据", parameters = {
            @Parameter(name = "id", description = "主键", required = true, in = ParameterIn.PATH)
    })
    @ApiOperationSupport(order = 5)
    public Result<Boolean> deleteById(@PathVariable String id) {

        if (sysUserService.removeById(id)) {
            return Result.success();
        }
        return Result.error();
    }

    @PostMapping("/delete")
    @Operation(summary = "通过主键删除多条数据")
    @ApiOperationSupport(order = 5)
    public Result<Boolean> deleteByIds(@RequestBody List<String> id) {
        log.info("删除的id；{}", id);

        if (sysUserService.removeBatchByIds(id)) {
            return Result.success();
        }
        return Result.error();
    }

}